package com.lj.frame.file.controller;

import com.alibaba.fastjson.JSONObject;
import com.lj.commons.consts.Constants;
import com.lj.commons.exception.YerException;
import com.lj.commons.reponse.Result;
import com.lj.frame.file.entity.UploadFile;
import com.lj.frame.file.service.impl.FileServiceImpl;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.nio.charset.StandardCharsets;

@RequiredArgsConstructor
@Slf4j
@RequestMapping("file")
@RestController
public class FileController {

    private final FileServiceImpl fileService;


    @ApiOperation(value = "上传文件", response = Result.class)
    @PostMapping("upload")
    public Result upload(MultipartFile multipartFile, @RequestBody JSONObject params) throws Exception, YerException {
        Boolean isTemp = params.getBoolean("isTemp");

        UploadFile uploadFile = UploadFile.createFromMultiFile(multipartFile, isTemp);
        //检查是否合法
        uploadFile.checkSafe();

        String path = null;
        UploadFile has = fileService.findByMd5(uploadFile.getMd5());
        if (has != null){
            path = has.getPath();
        }else{
            //根据设置的存储对象进行存储
            fileService.upload(uploadFile, multipartFile.getInputStream(), multipartFile.getContentType());
            //存储
            path = uploadFile.getPath();
        }
        return Result.ok().setContent("上传成功", path);
    }


    /**
     * 文件流回显
     * */
    @ApiOperation(value = "下载文件")
    @GetMapping("p_download/{path}")
    public void publicDownload(@PathVariable("path")String path,
                               HttpServletRequest request,
                               HttpServletResponse response) {
        try{
            //查询当前配置
            UploadFile uploadFile = fileService.findByPath(path);
            if ( uploadFile == null ){
                response.setStatus(404);
                response.getOutputStream().write("没有查询到相关文件".getBytes(StandardCharsets.UTF_8));
                return;
            }

            String clientHost = null;
            if( !StringUtils.hasLength(clientHost) ){
                //配置的是本地地址-下载本地数据
                response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
                response.setHeader("Content-Disposition", String.format("attachment;filename=%s", uploadFile.getName()));
                response.setHeader("Expires", "0");
                response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
                response.setHeader("Pragma", "no-cache");
                response.setContentType("application/octet-stream;charset=utf-8");
                BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
                //循环输出数据流
                uploadFile.download(outputStream, clientHost);
            }else{
                //远程端口-直接跳转给出路径地址,否则输出文件流
                response.setStatus(302);
                response.setHeader(Constants.CommonHeaders.LOCATION, clientHost+uploadFile.getPath());
            }
        }catch (Exception e){
            //出现错误
            response.setStatus(404);
            response.setContentType("txt/plain;charset=utf-8");
            log.error("文件下载:"+path, e);
        }finally {
        }
    }

}
